package com.gray.wow.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gray.wow.biz.NoticeBiz;
import com.gray.wow.common.*;
import com.gray.wow.domain.Notice;
import com.gray.wow.domain.PageModel;
import com.gray.wow.domain.User;

@Controller
@RequestMapping("/notice")
public class NoticeController {

	@Resource
	private NoticeBiz noticeBiz;

	
	@ExceptionHandler
	public String exp(Exception ex, HttpServletRequest request) {
		request.setAttribute("ex", ex);
		return "error";
	}

	// 图片管理
	@RequestMapping("/manage")
	public String manage(HttpServletRequest request,Integer page) {
		User user = (User) request.getSession().getAttribute("admin");
		if (user != null) {
			PageModel pm=noticeBiz.getNotice(Page.HALF_DEFAULT_PAGESIZE, page);
			request.setAttribute("pageModel", pm);
			return "admin/notice/notice";
		}
		return null;
	}
	@RequestMapping("/add")
	public String add(Integer id,HttpServletRequest request) {
		User admin = (User) request.getSession().getAttribute("admin");
		if (admin != null) {
			return "admin/notice/saveNotice";
		}
		return null;
	}
	
	@RequestMapping("/edit")
	public String edit(Integer id,HttpServletRequest request) {
		User admin = (User) request.getSession().getAttribute("admin");
		if (admin != null) {
			Notice notice = noticeBiz.getNoticeById(id);
			if (notice != null) {
				request.setAttribute("notice", notice);
			}

			return "admin/notice/saveNotice";
		}
		return null;
	}
	
	@RequestMapping("/save")
	public String save(HttpServletRequest request,HttpServletResponse response,Notice notice) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			if(noticeBiz.saveNotice(notice))
			out.print("success");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "admin/notice/notice";
	}
	
	@RequestMapping("/delete")
	public String delete(int[] ids, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			User admin = (User) request.getSession().getAttribute("admin");
			if (admin != null) {
				if(noticeBiz.delNotice(ids))
				out.print("success");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
